package strategy

import (
	"log"
	"net/http/httptest"

	"github.com/afex/hystrix-go/hystrix"
	"github.com/gin-gonic/gin"
	"github.com/youkelike/gateway/core/lib"
	"github.com/youkelike/gateway/dao"
)

func InitCircuitConfig() {
	circuit := dao.CircuitConfig{}

	tx, err := lib.GetGormPool("default")
	if err != nil {
		log.Fatalf("InitCircuitConfig err: %v", err)
		return
	}
	c, _ := gin.CreateTestContext(httptest.NewRecorder())

	list, err := circuit.FindAll(c, tx)
	if err == nil {
		for i := range list {
			hystrix.ConfigureCommand(list[i].ServiceName, hystrix.CommandConfig{
				Timeout:                list[i].Timeout * 1000,
				MaxConcurrentRequests:  list[i].MaxConcurrentRequests,
				RequestVolumeThreshold: list[i].RequestVolumeThreshold,
				SleepWindow:            list[i].SleepWindow * 1000,
				ErrorPercentThreshold:  list[i].ErrorPercentThreshold,
			})
		}
	}
}

func UpdateCircuitConfig(serviceName string, circuitConfig *dao.CircuitConfig) {
	hystrix.ConfigureCommand(serviceName, hystrix.CommandConfig{
		Timeout:                circuitConfig.Timeout,
		MaxConcurrentRequests:  circuitConfig.MaxConcurrentRequests,
		RequestVolumeThreshold: circuitConfig.RequestVolumeThreshold,
		SleepWindow:            circuitConfig.SleepWindow,
		ErrorPercentThreshold:  circuitConfig.ErrorPercentThreshold,
	})
}
